{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 语音识别测试-百度API"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "API_KEY = '2fFGTG0tqIZ7ZjLUlR52LIhv'\n",
    "SECRET_KEY = 'pzBcP0b8Ez2f8PrXGVFZlRHMBhsc97on'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# coding=utf-8\n",
    "\n",
    "import sys\n",
    "import json\n",
    "import base64\n",
    "import time\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "    timer = time.perf_counter\n",
    "else:\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "    if sys.platform == \"win32\":\n",
    "        timer = time.clock\n",
    "    else:\n",
    "        # On most other platforms the best timer is time.time()\n",
    "        timer = time.time\n",
    "\n",
    "API_KEY = '2fFGTG0tqIZ7ZjLUlR52LIhv'\n",
    "SECRET_KEY = 'pzBcP0b8Ez2f8PrXGVFZlRHMBhsc97on'\n",
    "\n",
    "# 需要识别的文件\n",
    "AUDIO_FILE = './speech-demo-master/rest-api-asr/python/audio/16k.pcm'  # 只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "# 文件格式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 文件格式\n",
    "FORMAT = AUDIO_FILE[-3:]  # 文件后缀只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "\n",
    "CUID = '123456PYTHON'\n",
    "# 采样率\n",
    "RATE = 16000  # 固定值\n",
    "\n",
    "# 普通版\n",
    "\n",
    "DEV_PID = 1537  # 1537 表示识别普通话，使用输入法模型。根据文档填写PID，选择语言及识别模型\n",
    "ASR_URL = 'http://vop.baidu.com/server_api'\n",
    "SCOPE = 'audio_voice_assistant_get'  # 有此scope表示有asr能力，没有请在网页里勾选，非常旧的应用可能没有\n",
    "\n",
    "#测试自训练平台需要打开以下信息， 自训练平台模型上线后，您会看见 第二步：“”获取专属模型参数pid:8001，modelid:1234”，按照这个信息获取 dev_pid=8001，lm_id=1234\n",
    "# DEV_PID = 8001 ;   \n",
    "# LM_ID = 1234 ;\n",
    "\n",
    "# 极速版 打开注释的话请填写自己申请的appkey appSecret ，并在网页中开通极速版（开通后可能会收费）\n",
    "\n",
    "# DEV_PID = 80001\n",
    "# ASR_URL = 'http://vop.baidu.com/pro_api'\n",
    "# SCOPE = 'brain_enhanced_asr'  # 有此scope表示有极速版能力，没有请在网页里开通极速版\n",
    "\n",
    "# 忽略scope检查，非常旧的应用可能没有\n",
    "# SCOPE = False\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN start \"\"\"\n",
    "\n",
    "TOKEN_URL = 'http://aip.baidubce.com/oauth/2.0/token'\n",
    "\n",
    "\n",
    "def fetch_token(API_KEY,SECRET_KEY):\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode( 'utf-8')\n",
    "    req = Request(TOKEN_URL, post_data)\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str =  result_str.decode()\n",
    "\n",
    "    print(result_str)\n",
    "    result = json.loads(result_str)\n",
    "    print(result)\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        print(SCOPE)\n",
    "        if SCOPE and (not SCOPE in result['scope'].split(' ')):  # SCOPE = False 忽略检查\n",
    "            raise DemoError('scope is not correct')\n",
    "        print('SUCCESS WITH TOKEN: %s  EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "\"\"\"  TOKEN end \"\"\"\n",
    "\n",
    "# if __name__ == '__main__':\n",
    "#     token = fetch_token()\n",
    "    \n",
    "    \n",
    "def asr(token,AUDIO_FILE):\n",
    "    speech_data = []\n",
    "    with open(AUDIO_FILE, 'rb') as speech_file:\n",
    "        speech_data = speech_file.read()\n",
    "\n",
    "    length = len(speech_data)\n",
    "    if length == 0:\n",
    "        raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)\n",
    "    speech = base64.b64encode(speech_data)\n",
    "    if (IS_PY3):\n",
    "        speech = str(speech, 'utf-8')\n",
    "    params = {'dev_pid': DEV_PID,\n",
    "             #\"lm_id\" : LM_ID,    #测试自训练平台开启此项\n",
    "              'format': FORMAT,\n",
    "              'rate': RATE,\n",
    "              'token': token,\n",
    "              'cuid': CUID,\n",
    "              'channel': 1,\n",
    "              'speech': speech,\n",
    "              'len': length\n",
    "              }\n",
    "    post_data = json.dumps(params, sort_keys=False)\n",
    "    # print post_data\n",
    "    req = Request(ASR_URL, post_data.encode('utf-8'))\n",
    "    req.add_header('Content-Type', 'application/json')\n",
    "    try:\n",
    "        begin = timer()\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "        print (\"Request time cost %f\" % (timer() - begin))\n",
    "    except URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "\n",
    "    if (IS_PY3):\n",
    "        result_str = str(result_str, 'utf-8')\n",
    "#     print(result_str)\n",
    "    with open(\"result.txt\",\"w\") as of:\n",
    "        of.write(result_str)\n",
    "    return result_str\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"refresh_token\":\"25.ba300baaa5ec4e7771fd0f2b93794847.315360000.1968166269.282335-26255849\",\"expires_in\":2592000,\"session_key\":\"9mzdDxw9GyIlYCsZfryg+9pBDgETzgqeS3FAmQ3Rqg82lGGPdyftvu0V9oz0tJECwdU6UuUInVI69Q\\/rYlO7RTl2j2RQ\\/A==\",\"access_token\":\"24.48ba2c46566076a552eeb35fdcafc3e0.2592000.1655398269.282335-26255849\",\"scope\":\"audio_voice_assistant_get brain_enhanced_asr audio_tts_post brain_speech_realtime public brain_all_scope brain_asr_async wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test\\u6743\\u9650 vis-classify_flower lpq_\\u5f00\\u653e cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_\\u5f00\\u653eScope vis-ocr_\\u865a\\u62df\\u4eba\\u7269\\u52a9\\u7406 idl-video_\\u865a\\u62df\\u4eba\\u7269\\u52a9\\u7406 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx\",\"session_secret\":\"d880b7dbd43a300c5bb23a60c7dda1c7\"}\n",
      "\n",
      "{'refresh_token': '25.ba300baaa5ec4e7771fd0f2b93794847.315360000.1968166269.282335-26255849', 'expires_in': 2592000, 'session_key': '9mzdDxw9GyIlYCsZfryg+9pBDgETzgqeS3FAmQ3Rqg82lGGPdyftvu0V9oz0tJECwdU6UuUInVI69Q/rYlO7RTl2j2RQ/A==', 'access_token': '24.48ba2c46566076a552eeb35fdcafc3e0.2592000.1655398269.282335-26255849', 'scope': 'audio_voice_assistant_get brain_enhanced_asr audio_tts_post brain_speech_realtime public brain_all_scope brain_asr_async wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx', 'session_secret': 'd880b7dbd43a300c5bb23a60c7dda1c7'}\n",
      "audio_voice_assistant_get\n",
      "SUCCESS WITH TOKEN: 24.48ba2c46566076a552eeb35fdcafc3e0.2592000.1655398269.282335-26255849  EXPIRES IN SECONDS: 2592000\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'24.48ba2c46566076a552eeb35fdcafc3e0.2592000.1655398269.282335-26255849'"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pan_token=fetch_token(API_KEY,SECRET_KEY)\n",
    "pan_token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Request time cost 0.483092\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'{\"corpus_no\":\"7098748877446844938\",\"err_msg\":\"success.\",\"err_no\":0,\"result\":[\"北京科技馆。\"],\"sn\":\"228419668831652806269\"}\\n'"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "asr(pan_token,'audio/16k.wav')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#  语音识别自动回复文本机器人\n",
    "\n",
    ">1.准备录制音频文件\n",
    "\n",
    ">2.调用语音识别,将音频转成文本(已完成)\n",
    "\n",
    ">3.文本自动回复 ()原理:问和答 I/O 输入和输出----特点:key:value"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 文本自动回复"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "qa={\n",
    "    \"你好\":\"你好呀有什么事吗\",\n",
    "    \"哈喽\":\"hhhhhhhhhh\"\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'你好呀有什么事吗'"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "qa.get(\"你好\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 安装"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 已在终端安装好"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: SpeechRecognition in c:\\users\\kingf\\anaconda3\\lib\\site-packages (3.8.1)\n",
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    }
   ],
   "source": [
    "pip install SpeechRecognition"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already up-to-date: SpeechRecognition in c:\\users\\kingf\\anaconda3\\lib\\site-packages (3.8.1)\n",
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    }
   ],
   "source": [
    "pip install --upgrade SpeechRecognition"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Collecting PyAudioNote: you may need to restart the kernel to use updated packages.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "  ERROR: Command errored out with exit status 1:\n",
      "   command: 'C:\\Users\\kingf\\anaconda3\\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '\"'\"'C:\\\\Users\\\\kingf\\\\AppData\\\\Local\\\\Temp\\\\pip-install-qi9gb0r5\\\\PyAudio\\\\setup.py'\"'\"'; __file__='\"'\"'C:\\\\Users\\\\kingf\\\\AppData\\\\Local\\\\Temp\\\\pip-install-qi9gb0r5\\\\PyAudio\\\\setup.py'\"'\"';f=getattr(tokenize, '\"'\"'open'\"'\"', open)(__file__);code=f.read().replace('\"'\"'\\r\\n'\"'\"', '\"'\"'\\n'\"'\"');f.close();exec(compile(code, __file__, '\"'\"'exec'\"'\"'))' bdist_wheel -d 'C:\\Users\\kingf\\AppData\\Local\\Temp\\pip-wheel-etxhqiof'\n",
      "       cwd: C:\\Users\\kingf\\AppData\\Local\\Temp\\pip-install-qi9gb0r5\\PyAudio\\\n",
      "  Complete output (9 lines):\n",
      "  running bdist_wheel\n",
      "  running build\n",
      "  running build_py\n",
      "  creating build\n",
      "  creating build\\lib.win-amd64-3.8"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "  Using cached PyAudio-0.2.11.tar.gz (37 kB)\n",
      "Building wheels for collected packages: PyAudio\n",
      "  Building wheel for PyAudio (setup.py): started\n",
      "  Building wheel for PyAudio (setup.py): finished with status 'error'\n",
      "  Running setup.py clean for PyAudio\n",
      "Failed to build PyAudio\n",
      "Installing collected packages: PyAudio\n",
      "    Running setup.py install for PyAudio: started\n",
      "    Running setup.py install for PyAudio: finished with status 'error'\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "  copying src\\pyaudio.py -> build\\lib.win-amd64-3.8\n",
      "  running build_ext\n",
      "  building '_portaudio' extension\n",
      "  error: Microsoft Visual C++ 14.0 is required. Get it with \"Build Tools for Visual Studio\": https://visualstudio.microsoft.com/downloads/\n",
      "  ----------------------------------------\n",
      "  ERROR: Failed building wheel for PyAudio\n",
      "    ERROR: Command errored out with exit status 1:\n",
      "     command: 'C:\\Users\\kingf\\anaconda3\\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '\"'\"'C:\\\\Users\\\\kingf\\\\AppData\\\\Local\\\\Temp\\\\pip-install-qi9gb0r5\\\\PyAudio\\\\setup.py'\"'\"'; __file__='\"'\"'C:\\\\Users\\\\kingf\\\\AppData\\\\Local\\\\Temp\\\\pip-install-qi9gb0r5\\\\PyAudio\\\\setup.py'\"'\"';f=getattr(tokenize, '\"'\"'open'\"'\"', open)(__file__);code=f.read().replace('\"'\"'\\r\\n'\"'\"', '\"'\"'\\n'\"'\"');f.close();exec(compile(code, __file__, '\"'\"'exec'\"'\"'))' install --record 'C:\\Users\\kingf\\AppData\\Local\\Temp\\pip-record-76jszwev\\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\\Users\\kingf\\anaconda3\\Include\\PyAudio'\n",
      "         cwd: C:\\Users\\kingf\\AppData\\Local\\Temp\\pip-install-qi9gb0r5\\PyAudio\\\n",
      "    Complete output (9 lines):\n",
      "    running install\n",
      "    running build\n",
      "    running build_py\n",
      "    creating build\n",
      "    creating build\\lib.win-amd64-3.8\n",
      "    copying src\\pyaudio.py -> build\\lib.win-amd64-3.8\n",
      "    running build_ext\n",
      "    building '_portaudio' extension\n",
      "    error: Microsoft Visual C++ 14.0 is required. Get it with \"Build Tools for Visual Studio\": https://visualstudio.microsoft.com/downloads/\n",
      "    ----------------------------------------\n",
      "ERROR: Command errored out with exit status 1: 'C:\\Users\\kingf\\anaconda3\\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '\"'\"'C:\\\\Users\\\\kingf\\\\AppData\\\\Local\\\\Temp\\\\pip-install-qi9gb0r5\\\\PyAudio\\\\setup.py'\"'\"'; __file__='\"'\"'C:\\\\Users\\\\kingf\\\\AppData\\\\Local\\\\Temp\\\\pip-install-qi9gb0r5\\\\PyAudio\\\\setup.py'\"'\"';f=getattr(tokenize, '\"'\"'open'\"'\"', open)(__file__);code=f.read().replace('\"'\"'\\r\\n'\"'\"', '\"'\"'\\n'\"'\"');f.close();exec(compile(code, __file__, '\"'\"'exec'\"'\"'))' install --record 'C:\\Users\\kingf\\AppData\\Local\\Temp\\pip-record-76jszwev\\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\\Users\\kingf\\anaconda3\\Include\\PyAudio' Check the logs for full command output.\n"
     ]
    }
   ],
   "source": [
    "pip install PyAudio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install pipwin"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "failed to create process.\n"
     ]
    }
   ],
   "source": [
    "!pipwin install PyAudio"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 实践"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"refresh_token\":\"25.8e359c7a6d466aa03ed01270b06f8178.315360000.1968167377.282335-26255849\",\"expires_in\":2592000,\"session_key\":\"9mzdWW2C2\\/zeL2B6iVDmU0rcI5AGXBQnkWH1Aw9McEbh6Tq7f4iuMbthdr\\/ztfpR55iSMgPCJZ6V9yFgPsICoJyN+PldQw==\",\"access_token\":\"24.b712d11d04b578886bcfe0bfc34535f6.2592000.1655399377.282335-26255849\",\"scope\":\"audio_voice_assistant_get brain_enhanced_asr audio_tts_post brain_speech_realtime public brain_all_scope brain_asr_async wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test\\u6743\\u9650 vis-classify_flower lpq_\\u5f00\\u653e cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_\\u5f00\\u653eScope vis-ocr_\\u865a\\u62df\\u4eba\\u7269\\u52a9\\u7406 idl-video_\\u865a\\u62df\\u4eba\\u7269\\u52a9\\u7406 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx\",\"session_secret\":\"668d44fdbcf1b9e036488dbd51e6b9f6\"}\n",
      "\n",
      "{'refresh_token': '25.8e359c7a6d466aa03ed01270b06f8178.315360000.1968167377.282335-26255849', 'expires_in': 2592000, 'session_key': '9mzdWW2C2/zeL2B6iVDmU0rcI5AGXBQnkWH1Aw9McEbh6Tq7f4iuMbthdr/ztfpR55iSMgPCJZ6V9yFgPsICoJyN+PldQw==', 'access_token': '24.b712d11d04b578886bcfe0bfc34535f6.2592000.1655399377.282335-26255849', 'scope': 'audio_voice_assistant_get brain_enhanced_asr audio_tts_post brain_speech_realtime public brain_all_scope brain_asr_async wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx', 'session_secret': '668d44fdbcf1b9e036488dbd51e6b9f6'}\n",
      "audio_voice_assistant_get\n",
      "SUCCESS WITH TOKEN: 24.b712d11d04b578886bcfe0bfc34535f6.2592000.1655399377.282335-26255849  EXPIRES IN SECONDS: 2592000\n",
      "Request time cost 0.681206\n"
     ]
    }
   ],
   "source": [
    "# 1.录制音频文件\n",
    "import speech_recognition\n",
    "r = speech_recognition.Recognizer()\n",
    "# 通过调用电脑的麦克风进行音频的获取\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到wav文件中\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))\n",
    "    \n",
    "# 2.调用百度asr\n",
    "pan_token=fetch_token(API_KEY,SECRET_KEY)\n",
    "asr_result=eval(asr(pan_token,'audio/16k.wav'))['result'][0][:-1] #  eval(将str to dict)\n",
    "\n",
    "# 3.文本自动回复\n",
    "qa.get(asr_result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
